import { createRouter, createWebHistory } from 'vue-router'
import index from '../views/index.vue'
import UserLogin from '../views/user/UserLogin.vue'
import UserRegister from '../views/user/UserRegister.vue'
import userStore from '../store/index'
import UserInfo from '../views/user/UserInfo.vue'
import UserEdit from '../views/user/UserEdit.vue'
import ArticleInfo from '../views/article/ArticleInfo.vue'
import Article from '../views/article/Article.vue'  
import Search from '../views/Search.vue'
import Contact from '../views/contact/contact.vue'
const router = createRouter({
  history: createWebHistory("/"),
  routes: [
    {
        path: '/',
        redirect: '/index',
    },
    {
        path: '/index',
        name: 'index',
        component: index,
        meta: { requiresAuth: true } // 添加元信息，表示需要登录
    },
    {
        path: '/login',
        name: 'login',
        component: UserLogin,
    },
    {
        path: '/register',
        name: 'register',
        component: UserRegister,
    },
    {
      path:'/userinfo',
      name:'userinfo',
      component: UserInfo,
      meta: { requiresAuth: true } // 添加元信息，表示需要登录
    },{
      path:'/useredit',
      name:'useredit',
      component: UserEdit,
      meta: { requiresAuth: true } // 添加元信息，表示需要登录
    },{
      path:'/articleinfo',
      name:'articleinfo',
      component: ArticleInfo,
      meta: { requiresAuth: true } // 添加元信息，表示需要登录
    },{
      path:'/article',
      name:'article',
      component: Article,
      meta: { requiresAuth: true } // 添加元信息，表示需要登录
    },{
      path:'/search',
      name:'search',
      component: Search,
      meta: { requiresAuth: true } // 添加元信息，表示需要登录
    },{
      path:'/contact',
      name:'contact',
      component: Contact,
      meta: { requiresAuth: true } // 添加元信息，表示需要登录
    }
  ],
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  const store = userStore();
  const user = store.getUser();

  // 如果用户已登录且访问的是登录页或注册页，跳转到首页
  if ((to.name === 'login' || to.name === 'register') && user.username) {
    next({ name: 'index' });
  } 
  // 检查目标路由是否需要登录
  else if (to.meta.requiresAuth && !user.username) {
    next({ name: 'login' }); // 跳转到登录页
  } else {
    next(); // 继续导航
  }
})

export default router
